{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a786c77c",
   "metadata": {},
   "source": [
    "# LangChain: Memory\n",
    "\n",
    "## Outline\n",
    "* ConversationBufferMemory\n",
    "* ConversationBufferWindowMemory\n",
    "* ConversationTokenBufferMemory\n",
    "* ConversationSummaryMemory"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1297dcd5",
   "metadata": {},
   "source": [
    "## ConversationBufferMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a1f518f5",
   "metadata": {
    "height": 131,
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv()) # read local .env file\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2301270b-7a69-40f8-9934-f840499b6ae9",
   "metadata": {},
   "source": [
    "Note: LLM's do not always produce the same results. When executing the code in your notebook, you may get slightly different answers that those in the video."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ce0924a2-ce2d-44ba-a806-c1195720c237",
   "metadata": {
    "height": 233
   },
   "outputs": [],
   "source": [
    "# account for deprecation of LLM model\n",
    "import datetime\n",
    "# Get the current date\n",
    "current_date = datetime.datetime.now().date()\n",
    "\n",
    "# Define the date after which the model should be set to \"gpt-3.5-turbo\"\n",
    "target_date = datetime.date(2024, 6, 12)\n",
    "\n",
    "# Set the model variable based on the current date\n",
    "if current_date > target_date:\n",
    "    llm_model = \"gpt-3.5-turbo\"\n",
    "else:\n",
    "    llm_model = \"gpt-3.5-turbo-0301\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "20ad6fe2",
   "metadata": {
    "height": 63,
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.chains import ConversationChain\n",
    "from langchain.memory import ConversationBufferMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "88bdf13d",
   "metadata": {
    "height": 131,
    "tags": []
   },
   "outputs": [],
   "source": [
    "llm = ChatOpenAI(temperature=0.0, model=llm_model)\n",
    "memory = ConversationBufferMemory()\n",
    "conversation = ConversationChain(\n",
    "    llm=llm, \n",
    "    memory = memory,\n",
    "    verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "66cdad7a",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ConversationBufferMemory(chat_memory=ChatMessageHistory(messages=[]), output_key=None, input_key=None, return_messages=False, human_prefix='Human', ai_prefix='AI', memory_key='history')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "069995b1",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ConversationChain(memory=ConversationBufferMemory(chat_memory=ChatMessageHistory(messages=[]), output_key=None, input_key=None, return_messages=False, human_prefix='Human', ai_prefix='AI', memory_key='history'), callbacks=None, callback_manager=None, verbose=True, prompt=PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\\n\\nCurrent conversation:\\n{history}\\nHuman: {input}\\nAI:', template_format='f-string', validate_template=True), llm=ChatOpenAI(verbose=False, callbacks=None, callback_manager=None, client=<class 'openai.api_resources.chat_completion.ChatCompletion'>, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key=None, openai_api_base=None, openai_organization=None, request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None), output_key='response', input_key='input')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "db24677d",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "\n",
      "Human: Hi, my name is Andrew\n",
      "AI:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"Hello Andrew! It's nice to meet you. How can I assist you today?\""
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"Hi, my name is Andrew\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "cc3ef937",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "Human: Hi, my name is Andrew\n",
      "AI: Hello Andrew! It's nice to meet you. How can I assist you today?\n",
      "Human: What is 1+1?\n",
      "AI:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'1+1 equals 2. Is there anything else you would like to know?'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"What is 1+1?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "acf3339a",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "Human: Hi, my name is Andrew\n",
      "AI: Hello Andrew! It's nice to meet you. How can I assist you today?\n",
      "Human: What is 1+1?\n",
      "AI: 1+1 equals 2. Is there anything else you would like to know?\n",
      "Human: What is my name?\n",
      "AI:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Your name is Andrew.'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"What is my name?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "2529400d",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Human: Hi, my name is Andrew\n",
      "AI: Hello Andrew! It's nice to meet you. How can I assist you today?\n",
      "Human: What is 1+1?\n",
      "AI: 1+1 equals 2. Is there anything else you would like to know?\n",
      "Human: What is my name?\n",
      "AI: Your name is Andrew.\n"
     ]
    }
   ],
   "source": [
    "print(memory.buffer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "5018cb0a",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': \"Human: Hi, my name is Andrew\\nAI: Hello Andrew! It's nice to meet you. How can I assist you today?\\nHuman: What is 1+1?\\nAI: 1+1 equals 2. Is there anything else you would like to know?\\nHuman: What is my name?\\nAI: Your name is Andrew.\"}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "0cae8ace",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "load_memory_variables() missing 1 required positional argument: 'inputs'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[12], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mmemory\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mload_memory_variables\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n",
      "\u001b[0;31mTypeError\u001b[0m: load_memory_variables() missing 1 required positional argument: 'inputs'"
     ]
    }
   ],
   "source": [
    "memory.load_memory_variables()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "14219b70",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [],
   "source": [
    "memory = ConversationBufferMemory()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "a36e9905",
   "metadata": {
    "height": 46,
    "tags": []
   },
   "outputs": [],
   "source": [
    "memory.save_context({\"input\": \"Hi\"}, \n",
    "                    {\"output\": \"What's up\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "bc1b7943",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Human: Hi\\nAI: What's up\""
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.buffer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "61631b1f",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Human: Hi\n",
      "AI: What's up\n"
     ]
    }
   ],
   "source": [
    "print(memory.buffer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "a2fdf9ec",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': \"Human: Hi\\nAI: What's up\"}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "7ca79256",
   "metadata": {
    "height": 46,
    "tags": []
   },
   "outputs": [],
   "source": [
    "memory.save_context({\"input\": \"Not much, just hanging\"}, \n",
    "                    {\"output\": \"Cool\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "890a4497",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': \"Human: Hi\\nAI: What's up\\nHuman: Not much, just hanging\\nAI: Cool\"}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f153e3fe",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Human: Hi\n",
      "AI: What's up\n",
      "Human: Not much, just hanging\n",
      "AI: Cool\n"
     ]
    }
   ],
   "source": [
    "print(memory.buffer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf98e9ff",
   "metadata": {
    "tags": []
   },
   "source": [
    "## ConversationBufferWindowMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "66eeccc3",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.memory import ConversationBufferWindowMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "3ea6233e",
   "metadata": {
    "height": 46,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ConversationBufferWindowMemory(chat_memory=ChatMessageHistory(messages=[]), output_key=None, input_key=None, return_messages=False, human_prefix='Human', ai_prefix='AI', memory_key='history', k=1)"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory = ConversationBufferWindowMemory(k=1)\n",
    "memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "dc4553fb",
   "metadata": {
    "height": 97,
    "tags": []
   },
   "outputs": [],
   "source": [
    "memory.save_context({\"input\": \"Hi\"},\n",
    "                    {\"output\": \"What's up\"})\n",
    "memory.save_context({\"input\": \"Not much, just hanging\"},\n",
    "                    {\"output\": \"Cool\"})\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "6a788403",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': 'Human: Not much, just hanging\\nAI: Cool'}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "4087bc87",
   "metadata": {
    "height": 148,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ConversationChain(memory=ConversationBufferWindowMemory(chat_memory=ChatMessageHistory(messages=[]), output_key=None, input_key=None, return_messages=False, human_prefix='Human', ai_prefix='AI', memory_key='history', k=1), callbacks=None, callback_manager=None, verbose=False, prompt=PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\\n\\nCurrent conversation:\\n{history}\\nHuman: {input}\\nAI:', template_format='f-string', validate_template=True), llm=ChatOpenAI(verbose=False, callbacks=None, callback_manager=None, client=<class 'openai.api_resources.chat_completion.ChatCompletion'>, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key=None, openai_api_base=None, openai_organization=None, request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None), output_key='response', input_key='input')"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "llm = ChatOpenAI(temperature=0.0, model=llm_model)\n",
    "memory = ConversationBufferWindowMemory(k=1)\n",
    "conversation = ConversationChain(\n",
    "    llm=llm, \n",
    "    memory = memory,\n",
    "    verbose=False\n",
    ")\n",
    "conversation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "4faaa952",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Hello Andrew! It's nice to meet you. How can I assist you today?\""
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"Hi, my name is Andrew\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "bb20ddaa",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1+1 equals 2. Is there anything else you would like to know?'"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"What is 1+1?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "489b2194",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"I'm sorry, I do not have access to personal information such as your name. Is there anything else you would like to know?\""
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"What is my name?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2931b92",
   "metadata": {},
   "source": [
    "## ConversationTokenBufferMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "9f6d063c",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [],
   "source": [
    "#!pip install tiktoken"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "fb9020ed",
   "metadata": {
    "height": 63,
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.memory import ConversationTokenBufferMemory\n",
    "from langchain.llms import OpenAI\n",
    "llm = ChatOpenAI(temperature=0.0, model=llm_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "43582ee6",
   "metadata": {
    "height": 148,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[AIMessage(content='Amazing!', additional_kwargs={}, example=False),\n",
       " HumanMessage(content='Backpropagation is what?', additional_kwargs={}, example=False),\n",
       " AIMessage(content='Beautiful!', additional_kwargs={}, example=False),\n",
       " HumanMessage(content='Chatbots are what?', additional_kwargs={}, example=False),\n",
       " AIMessage(content='Charming!', additional_kwargs={}, example=False)]"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=50)\n",
    "memory.save_context({\"input\": \"AI is what?!\"},\n",
    "                    {\"output\": \"Amazing!\"})\n",
    "memory.save_context({\"input\": \"Backpropagation is what?\"},\n",
    "                    {\"output\": \"Beautiful!\"})\n",
    "memory.save_context({\"input\": \"Chatbots are what?\"}, \n",
    "                    {\"output\": \"Charming!\"})\n",
    "memory.buffer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "161b777b",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[AIMessage(content='Amazing!', additional_kwargs={}, example=False), HumanMessage(content='Backpropagation is what?', additional_kwargs={}, example=False), AIMessage(content='Beautiful!', additional_kwargs={}, example=False), HumanMessage(content='Chatbots are what?', additional_kwargs={}, example=False), AIMessage(content='Charming!', additional_kwargs={}, example=False)]\n"
     ]
    }
   ],
   "source": [
    "print(memory.buffer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "284288e1",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': 'AI: Amazing!\\nHuman: Backpropagation is what?\\nAI: Beautiful!\\nHuman: Chatbots are what?\\nAI: Charming!'}"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "6f9283ce",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AI: Amazing!\n",
      "Human: Backpropagation is what?\n",
      "AI: Beautiful!\n",
      "Human: Chatbots are what?\n",
      "AI: Charming!\n"
     ]
    }
   ],
   "source": [
    "print(memory.load_memory_variables({})['history'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ff55d5d",
   "metadata": {},
   "source": [
    "## ConversationSummaryMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "72dcf8b1",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.memory import ConversationSummaryBufferMemory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "63476241",
   "metadata": {
    "height": 199,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ConversationSummaryBufferMemory(human_prefix='Human', ai_prefix='AI', llm=ChatOpenAI(verbose=False, callbacks=None, callback_manager=None, client=<class 'openai.api_resources.chat_completion.ChatCompletion'>, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key=None, openai_api_base=None, openai_organization=None, request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None), prompt=PromptTemplate(input_variables=['summary', 'new_lines'], output_parser=None, partial_variables={}, template='Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\\n\\nEXAMPLE\\nCurrent summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\\n\\nNew lines of conversation:\\nHuman: Why do you think artificial intelligence is a force for good?\\nAI: Because artificial intelligence will help humans reach their full potential.\\n\\nNew summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\\nEND OF EXAMPLE\\n\\nCurrent summary:\\n{summary}\\n\\nNew lines of conversation:\\n{new_lines}\\n\\nNew summary:', template_format='f-string', validate_template=True), summary_message_cls=<class 'langchain.schema.SystemMessage'>, chat_memory=ChatMessageHistory(messages=[]), output_key=None, input_key=None, return_messages=False, max_token_limit=100, moving_summary_buffer='', memory_key='history')"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# create a long string\n",
    "schedule = \"There is a meeting at 8am with your product team. \\\n",
    "You will need your powerpoint presentation prepared. \\\n",
    "9am-12pm have time to work on your LangChain \\\n",
    "project which will go quickly because Langchain is such a powerful tool. \\\n",
    "At Noon, lunch at the italian resturant with a customer who is driving \\\n",
    "from over an hour away to meet you to understand the latest in AI. \\\n",
    "Be sure to bring your laptop to show the latest LLM demo.\"\n",
    "\n",
    "memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100)\n",
    "memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "37f6b0a5",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n",
      "\n",
      "EXAMPLE\n",
      "Current summary:\n",
      "The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n",
      "\n",
      "New lines of conversation:\n",
      "Human: Why do you think artificial intelligence is a force for good?\n",
      "AI: Because artificial intelligence will help humans reach their full potential.\n",
      "\n",
      "New summary:\n",
      "The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\n",
      "END OF EXAMPLE\n",
      "\n",
      "Current summary:\n",
      "{summary}\n",
      "\n",
      "New lines of conversation:\n",
      "{new_lines}\n",
      "\n",
      "New summary:\n"
     ]
    }
   ],
   "source": [
    "print(memory.prompt.template)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "4a5b238f",
   "metadata": {
    "height": 114,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ConversationSummaryBufferMemory(human_prefix='Human', ai_prefix='AI', llm=ChatOpenAI(verbose=False, callbacks=None, callback_manager=None, client=<class 'openai.api_resources.chat_completion.ChatCompletion'>, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key=None, openai_api_base=None, openai_organization=None, request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None), prompt=PromptTemplate(input_variables=['summary', 'new_lines'], output_parser=None, partial_variables={}, template='Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\\n\\nEXAMPLE\\nCurrent summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\\n\\nNew lines of conversation:\\nHuman: Why do you think artificial intelligence is a force for good?\\nAI: Because artificial intelligence will help humans reach their full potential.\\n\\nNew summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\\nEND OF EXAMPLE\\n\\nCurrent summary:\\n{summary}\\n\\nNew lines of conversation:\\n{new_lines}\\n\\nNew summary:', template_format='f-string', validate_template=True), summary_message_cls=<class 'langchain.schema.SystemMessage'>, chat_memory=ChatMessageHistory(messages=[]), output_key=None, input_key=None, return_messages=False, max_token_limit=100, moving_summary_buffer='The human and AI exchange greetings and discuss the schedule for the day, including a meeting with the product team, work on the LangChain project, and a lunch meeting with a customer interested in AI.', memory_key='history')"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.save_context({\"input\": \"Hello\"}, {\"output\": \"What's up\"})\n",
    "memory.save_context({\"input\": \"Not much, just hanging\"},\n",
    "                    {\"output\": \"Cool\"})\n",
    "memory.save_context({\"input\": \"What is on the schedule today?\"}, \n",
    "                    {\"output\": f\"{schedule}\"})\n",
    "memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "cd244ca4",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n",
      "\n",
      "EXAMPLE\n",
      "Current summary:\n",
      "The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n",
      "\n",
      "New lines of conversation:\n",
      "Human: Why do you think artificial intelligence is a force for good?\n",
      "AI: Because artificial intelligence will help humans reach their full potential.\n",
      "\n",
      "New summary:\n",
      "The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\n",
      "END OF EXAMPLE\n",
      "\n",
      "Current summary:\n",
      "{summary}\n",
      "\n",
      "New lines of conversation:\n",
      "{new_lines}\n",
      "\n",
      "New summary:\n"
     ]
    }
   ],
   "source": [
    "print(memory.prompt.template)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "2e4ecabe",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': 'System: The human and AI exchange greetings and discuss the schedule for the day, including a meeting with the product team, work on the LangChain project, and a lunch meeting with a customer interested in AI.'}"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "6728edba",
   "metadata": {
    "height": 114,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ConversationChain(memory=ConversationSummaryBufferMemory(human_prefix='Human', ai_prefix='AI', llm=ChatOpenAI(verbose=False, callbacks=None, callback_manager=None, client=<class 'openai.api_resources.chat_completion.ChatCompletion'>, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key=None, openai_api_base=None, openai_organization=None, request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None), prompt=PromptTemplate(input_variables=['summary', 'new_lines'], output_parser=None, partial_variables={}, template='Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\\n\\nEXAMPLE\\nCurrent summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\\n\\nNew lines of conversation:\\nHuman: Why do you think artificial intelligence is a force for good?\\nAI: Because artificial intelligence will help humans reach their full potential.\\n\\nNew summary:\\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\\nEND OF EXAMPLE\\n\\nCurrent summary:\\n{summary}\\n\\nNew lines of conversation:\\n{new_lines}\\n\\nNew summary:', template_format='f-string', validate_template=True), summary_message_cls=<class 'langchain.schema.SystemMessage'>, chat_memory=ChatMessageHistory(messages=[]), output_key=None, input_key=None, return_messages=False, max_token_limit=100, moving_summary_buffer='The human and AI exchange greetings and discuss the schedule for the day, including a meeting with the product team, work on the LangChain project, and a lunch meeting with a customer interested in AI.', memory_key='history'), callbacks=None, callback_manager=None, verbose=True, prompt=PromptTemplate(input_variables=['history', 'input'], output_parser=None, partial_variables={}, template='The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\\n\\nCurrent conversation:\\n{history}\\nHuman: {input}\\nAI:', template_format='f-string', validate_template=True), llm=ChatOpenAI(verbose=False, callbacks=None, callback_manager=None, client=<class 'openai.api_resources.chat_completion.ChatCompletion'>, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key=None, openai_api_base=None, openai_organization=None, request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None), output_key='response', input_key='input')"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation = ConversationChain(\n",
    "    llm=llm, \n",
    "    memory = memory,\n",
    "    verbose=True\n",
    ")\n",
    "conversation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "9a221b1d",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "System: The human and AI exchange greetings and discuss the schedule for the day, including a meeting with the product team, work on the LangChain project, and a lunch meeting with a customer interested in AI.\n",
      "Human: What would be a good demo to show?\n",
      "AI:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'For the meeting with the product team, a good demo to show would be the latest prototype of the LangChain project, highlighting its key features and functionalities. This could include a live demonstration of the language translation capabilities, the user interface design, and any unique selling points that set LangChain apart from other language translation tools. Additionally, showcasing any recent updates or improvements made to the project would be beneficial to keep the team informed and engaged.'"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conversation.predict(input=\"What would be a good demo to show?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "bb582617",
   "metadata": {
    "height": 29,
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': 'System: The human and AI exchange greetings and discuss the schedule for the day, including a meeting with the product team, work on the LangChain project, and a lunch meeting with a customer interested in AI. The human asks what would be a good demo to show.\\nAI: For the meeting with the product team, a good demo to show would be the latest prototype of the LangChain project, highlighting its key features and functionalities. This could include a live demonstration of the language translation capabilities, the user interface design, and any unique selling points that set LangChain apart from other language translation tools. Additionally, showcasing any recent updates or improvements made to the project would be beneficial to keep the team informed and engaged.'}"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "29745b7f",
   "metadata": {
    "height": 29
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "124"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(memory.load_memory_variables({})['history'].split(' '))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6709b89-182e-4b7b-b811-1584dda20652",
   "metadata": {},
   "source": [
    "Reminder: Download your notebook to you local computer to save your work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ba827aa",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c07922b",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52696c8c",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48690d13",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85bba1f8",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96a62e89",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f953ad8d",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9bb2617",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be1989bf",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b1f8dca6",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9120949",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55849fb5",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94ae491b",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7c3aec3",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ae51a3f",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "06894001",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2fb674c",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5158f4c8",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cebe066",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65caee4d",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04799230",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30795c10",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "08ed59c4",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb43eee3",
   "metadata": {
    "height": 29
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
